package com.whu.dbpedia;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;

public class DbpediaToGraph {
	
	private String prefix = "/home/sanglei/vbox_share/DBpedia数据/处理过的数据";
	private String instancesWithClass = prefix + "/result_insance2class_types_op.nt";
	private String relMapping = prefix + "/temp_rel_mappingbased_properties_en.nt";
	private String edge = prefix +"/edge.txt";
	
	public HashMap<String,Integer> insertInstance(){
		HashMap<String,Integer> res = new HashMap<String,Integer>();
		BufferedReader br = null;
		try{
			br = new BufferedReader(new FileReader(new File(instancesWithClass)));
			int i = 1;
			while(br.ready()){
				res.put(br.readLine().split("\t")[0].trim(), i++);
			}
			System.out.println("HashMap 's size :"+res.size());
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return res;
	}

	public void createEdges(){
		BufferedReader br = null;
		HashMap<String,Integer>  res=null;
		StringBuffer sb = null;
		FileWriter fw = null;
		String prev = "";
		int sid=0;
		
		try{
			sb = new StringBuffer();
			res = insertInstance();
			br = new BufferedReader(new FileReader(new File(relMapping)));
			fw = new FileWriter(edge);
			while(br.ready()){
				String[] splits = br.readLine().trim().split("\t");
				if(splits.length == 3){
					if(!splits[0].trim().equals(prev)){
						Integer sInt;
						prev = splits[0];
						
						sInt = res.get(prev);
						
						if(sInt != null){
							sid = sInt;
						}else{
							continue;//这个instance没有找到对应的类
						}
						
						if(sb.length() > 300000){
							fw.write(sb.toString());
							sb = new StringBuffer();
						}
					}
					Integer eInt;
					if((eInt = res.get(splits[2])) == null){
						continue;//这个instance也没有找到对应的类
					}
					
					sb.append(sid + "\t" + eInt + "\t"+ splits[1] + "\n");
				}
				
			}
			
			fw.close();
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DbpediaToGraph dtg = new DbpediaToGraph();
		dtg.createEdges();
	}

}
